import React from 'react';
import { NavLink, Link } from 'react-router-dom';
import md5 from 'md5';
import { Form, Button, Input, Row, Col, Icon } from 'antd';
import { getStuLoginValidCode, studentLogin, validateMobilePhone } from '../api';
import * as utils from 'libs/utils';
import { withContext } from 'libs/context';

const ButtonGroup = Button.Group;
const FormItem = Form.Item;

class StudentLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      validCodeImg: '',
      showErr: false,
      errMessage: '',
    };
  }

  componentDidMount() {
    this.getStuLoginValidCode();
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      authority: nextProps.context.authority
    })
  }

  getStuLoginValidCode = () => {
    getStuLoginValidCode((res) => {
      this.setState({
        validCodeImg: res.data,
      });
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, values) => {
      const { password: _password, ...rest } = values;
      if (!err) {
        studentLogin({ password: md5(_password), ...rest, type: 1 }, (res) => {
          this.props.history.push('/student_center');
        }, (err) => {
          if(err.code == 6){
            form.setFields({
              validCode: {
                value: '',
                errors: [new Error(err.msg)],
              }
            })
          }else if(err.code == 7){
            form.setFields({
              password: {
                value: '',
                errors: [new Error(err.msg)],
              }
            })
          }
          this.setState({
            showErr: true,
            errMessage: utils.studentTransformErr(err),
          });
          this.getStuLoginValidCode();
        });
      }
    });
  }

  validateMobilePhone = (rule, value, callback) => {
    if (!value) {
      callback('手机号不能为空');
    } else if (value && !/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/.test(value)) {
      callback('手机号格式输入不正确！');
    } else {
      validateMobilePhone({ mobile: value }, res => {
        if (!res.data) {
          callback(<div>该手机号尚未注册，请前去<Link to="/student/register">注册</Link></div>);
        } else {
          callback();
        }
      })
    }
  }

  render() {
    const { validCodeImg, showErr, errMessage, authority } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="student-form">
        {/* <ButtonGroup className="btn-group">
          <NavLink className="btn-item" to="/student/password_login">
            <Button className="login" style={{ background: '#00284A', color: '#fff', borderRadius: '5px 0 0 5px' }}>密码登录</Button>
          </NavLink>
          <NavLink className="btn-item" to="/student/sms_login">
            <Button className="login" style={{ background: '#fff', color: '#00284a', borderRadius: '0 5px 5px 0' }}>短信登录</Button>
          </NavLink>
        </ButtonGroup> */}
        <Link to="/home" className="close"></Link>

        <div className="login-header">
          <NavLink className="btn-item" to="/student/password_login"><span>密码登录</span></NavLink>
          <NavLink className="btn-item" to="/student/sms_login"><span>短信登录</span></NavLink>
        </div>

        <Form layout="vertical" hideRequiredMark className="login-form" onSubmit={this.handleSubmit} onKeyDown={(e) => { if (e.keyCode == 13) { e.preventDefault(); } }}>
          <div className="valid-code-container">
            <FormItem  style={{ marginBottom: 0, height: 64 }} >
              <Row gutter={16}>
                <Col span={16}>
                  {getFieldDecorator('validCode', {
                    rules: [
                      { required: true, message: '验证码不能为空' },
                    ],
                  })(<p><Input 
                    size="large"
                    prefix={<Icon type="safety" style={{ color: '#bbb', fontSize: 18 }} />}
                    placeholder="请输入验证码" autoComplete="off" /></p>)}
                </Col>
                <Col span={6} onClick={this.getStuLoginValidCode}>
                  <img style={{ width: 100, height: 40, cursor: 'pointer' }} src={validCodeImg} alt="" />
                </Col>
              </Row>
            </FormItem>
          </div>
          <div className="mobile-phone-container">
            <FormItem  style={{ marginBottom: 0, height: 64 }}>
              {getFieldDecorator('mobilePhone', {
                rules: [
                  { required: true, message: ' ' },
                  // { message: '请输入正确的手机号', pattern: /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/}
                  { validator: this.validateMobilePhone },
                ],
              })(<Input 
                size="large"
                prefix={<Icon type="mobile" style={{ color: '#bbb', fontSize: 18 }} />}
                placeholder="请输入11位有效手机号码" autoComplete="off" />)}
            </FormItem>
          </div>
          
          <FormItem  style={{ marginBottom: 0, height: 64 }}>
            {getFieldDecorator('password', {
              rules: [
                { required: true, message: '密码不能为空' },
              ],
            })(<p><Input 
              size="large"
              prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
              type="password" autoComplete="off" placeholder="请输入密码" /></p>)}
          </FormItem>
         
          <Button type="primary" className="btn" htmlType="submit">登录</Button>
          <span className="link-to">
            <NavLink className="reset" to="/student/reset_password"><span>忘记密码?</span></NavLink>
            <span>还没有账号？请</span>
            <NavLink to="/student/register">立即注册</NavLink>
          </span>
        </Form>
      </div>
    );
  }
}

const WrapStudentLogin = Form.create()(StudentLogin);

export default withContext('authority')(WrapStudentLogin)
 // <p style={{
          //   width: '100%',
          //   height: 20,
          //   color: 'red', 
          //   textIndent: 8, 
          //   fontSize: 14, 
          //   visibility: `${showErr ? true : false}` 
          // }}
          // >
          // {errMessage}
          // </p>